﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SimpleInfrastructure.Message;
using SimpleInfrastructure.FrameWorks;

namespace SimpleModel.Cache.Redis
{
    public class RedisCacheService:ICacheService
    {
        private readonly string _keyPrefix;

        public RedisCacheService(string keyPrefix)
        {
            if (string.IsNullOrEmpty(keyPrefix))
            {
                throw new ArgumentNullException("keyPrefix is null or empty");
            }
            this._keyPrefix = keyPrefix;
        }

        public object GetObject<T>(string key)
        {
            return StackExchangeRedisHelper.Get<T>(GetCompletedKey(key));
        }

        public void Put<T>(string key, T value)
        {
            StackExchangeRedisHelper.Set(GetCompletedKey(key), value);
        }

        public void Put<T>(string key, T value, TimeSpan validFor)
        {
            StackExchangeRedisHelper.Set(GetCompletedKey(key), value, validFor);
        }

        public void Remove(string key)
        {
            StackExchangeRedisHelper.Remove(GetCompletedKey(key));
        }

        public void Clear()
        {
            StackExchangeRedisHelper.KeyDeleteWithPrefix(_keyPrefix);
        }
        private string GetCompletedKey(string key)
        {
            return _keyPrefix + key;
        }
    }
}
